package com.xiaoyuzhou;

import com.xiaoyuzhou.R;
import com.xiaoyuzhou.adapter.DataAdapter;
import com.xiaoyuzhou.logic.DataService;
import com.xiaoyuzhou.untity.Weather;
import com.xiaoyuzhou.utils.CalendarUtils;
import com.xiaoyuzhou.utils.SPUtils;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.provider.AlarmClock;
import android.widget.RemoteViews;

public class MyWidgetProvider extends AppWidgetProvider{
	
//	/**数字图片*/
//	public static final int[] number_imgIds = {R.drawable.number0, R.drawable.number1, R.drawable.number2, R.drawable.number3, R.drawable.number4, 
//		R.drawable.number5, R.drawable.number6, R.drawable.number7, R.drawable.number8, R.drawable.number9};
	
	/**打开应用*/
	public static final String ACTION_OPEN_APP = "open_app";
	/**分享*/
	public static final String ACTION_SHARE = "share";
	/**手动更新widget*/
	public static final String ACTION_WIDGET_UPDATE = "widget_update";
	public static final String ACTION_WIDGET_UPDATE_WEATHER = "widget_update_weather";
	
	/**更新时间*/
	public static final String ACTION_TIME_TICK = "time_tick";
	
	@Override
	public void onReceive(Context context, Intent intent) {
		super.onReceive(context, intent);
		System.out.println("onReceive:" + intent.getAction());
		AppWidgetManager appWidgetmanager = AppWidgetManager.getInstance(context);
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.transparentwidget);
		//根据不同的广播事件，进行不同的处理
		//widget刷新时，更新日期时间，从数据库中找到保存的天气信息显示
		if(intent.getAction().equals(AppWidgetManager.ACTION_APPWIDGET_UPDATE)) {
			updateDate(remoteViews,context);
			updateTime(remoteViews);
			updateWeather(context, null, remoteViews);
		}
		//用户将widget拖入桌面时
		else if(intent.getAction().equals(AppWidgetManager.ACTION_APPWIDGET_ENABLED)) {
			updateDate(remoteViews,context);
			updateTime(remoteViews);
			updateWeather(context, null, remoteViews);
		}
		//开机时，更新日期时间，从数据库中找到保存的天气信息显示
		else if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
			updateDate(remoteViews,context);
			updateTime(remoteViews);
			updateWeather(context, null, remoteViews);
		}
		//日期改变，更新日期
		else if(intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
//			context.sendBroadcast(new Intent(ACTION_REQUEST_WEATHER));
			updateDate(remoteViews,context);
			updateTime(remoteViews);
			updateWeather(context, null, remoteViews);
		} 
		//时间改变，更新时间
		else if(intent.getAction().equals(ACTION_TIME_TICK)) {
			updateTime(remoteViews);
		} 
		//更新天气
		else if(intent.getAction().equals(ACTION_WIDGET_UPDATE_WEATHER)) {
			updateWeather(context, intent, remoteViews);
		}
		//有网络连接后立刻刷新widget来获取最新数据
//		else if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
//			Bundle bundle = intent.getExtras();
//			//优先处理wifi情况
//			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//			boolean noNet = bundle.getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY);
//			if(!noNet) {
//				if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
//					//wifi可用时一定会请求网络，不需要检测上次更新时间
//					Intent i = new Intent(ACTION_REQUEST_WEATHER);
//					i.putExtra(DataService.CHECKLASTUPDATE, false);
//					context.sendBroadcast(i);
//				} else if(ConnectivityManager.isNetworkTypeValid(ConnectivityManager.TYPE_MOBILE)){
//					//有网络且上次刷新时间与当前时间相差12个小时时才重新请求
//					context.sendBroadcast(new Intent(ACTION_REQUEST_WEATHER));
//				}
//			}
//		}
		//预留接口，打开app和分享天气的响应
//		else if(intent.getAction().equals(ACTION_OPEN_APP)) {
//			Toast.makeText(context, "open app", Toast.LENGTH_LONG).show();
//		} else if(intent.getAction().equals(ACTION_SHARE)) {
//			Toast.makeText(context, "share", Toast.LENGTH_LONG).show();
//		}
		//刷新widget
		int[] appIds = appWidgetmanager.getAppWidgetIds(new ComponentName(context, MyWidgetProvider.class));
		appWidgetmanager.updateAppWidget(appIds, remoteViews);
	}
	
	/**
	 * 刷新天气信息
	 * @param context
	 * @param intent 若为空，则说明不是通过意图来传递数据，从数据库中取数据
	 * @param remoteViews
	 */
	private void updateWeather(Context context, Intent intent,
			RemoteViews remoteViews) {
		String weatherDetail = "";
		String temperature = "";
		String wind = "";
		String location = "";
		//如果意图不为空，从意图中拿数据
		if(intent != null) {
			weatherDetail = intent.getStringExtra(DataService.WEATHER_DETAIL);
			temperature = intent.getStringExtra(DataService.TEMPERATURE);
			wind = intent.getStringExtra(DataService.WIND);
			location = intent.getStringExtra(DataService.LOCATION);
		} else {//若为空，向数据库中拿数据
			location = SPUtils.readData(context, DataService.SP_NAME_LASTUPDATE, DataService.LOCATION);
			Weather weather = DataService.getWeatherFromData(context, location, CalendarUtils.getMonthDate());
			if(weather != null) {
				weatherDetail = weather.getWeatherDetail();
				temperature = weather.getTemperature();
				wind = weather.getWind();
			}
		}
		//更新UI
		if(weatherDetail != null && !weatherDetail.equals("")) {
			try {
				int id = DataAdapter.getWeaIconId(context, weatherDetail);
				remoteViews.setImageViewResource(R.id.widget_imgv_weathericon, id);
			} catch (Exception e) {
				e.printStackTrace();
			}
//			remoteViews.setTextViewText(R.id.widget_tv_note, context.getText(notesIds[id]));
			remoteViews.setTextViewText(R.id.widget_tv_weatherstate, weatherDetail);
//			remoteViews.setInt(R.id.widget_rl_left, "setBackgroundResource", bottom_imgIds[id]);
		}
		if(temperature != null && !temperature.equals("")) {
			remoteViews.setTextViewText(R.id.widget_tv_temperature, temperature);
		}
		if(wind != null && !wind.equals("")) {
			remoteViews.setTextViewText(R.id.widget_tv_wind, wind);
		}
		if(location != null && !location.equals("")) {
			remoteViews.setTextViewText(R.id.widget_tv_city, location);
		}
	}
	
	/**
	 * 刷新日期
	 */
	private void updateDate(RemoteViews remoteViews, Context context) {
		remoteViews.setTextViewText(R.id.widget_tv_chinesedate, CalendarUtils.getChineseDate());
		remoteViews.setTextViewText(R.id.widget_tv_date, CalendarUtils.getMonthDate());
		remoteViews.setTextViewText(R.id.widget_tv_dayofweek, CalendarUtils.getDayOfWeek());
//		remoteViews.setTextViewText(R.id.widget_tv_limit, context.getText(R.string.today_limit) 
//				+ LimitedCarUtils.getLimitedNumber(new Date()));
	}

	/**
	 * 刷新时间
	 */
	private void updateTime(RemoteViews remoteViews) {
		int hour = CalendarUtils.getHour();
//		remoteViews.setImageViewResource(R.id.imgv_hour1, number_imgIds[hour/10]);
//		remoteViews.setImageViewResource(R.id.imgv_hour2, number_imgIds[hour%10]);
		int minute = CalendarUtils.getMinute();
		String h=""+hour,m=""+minute;
		if(hour <= 9) {
			h = "0" + hour;
		}
		if(minute <= 9) {
			m = "0" + minute;
		}
		remoteViews.setTextViewText(R.id.widget_tv_time, h + ":" + m);
//		remoteViews.setImageViewResource(R.id.imgv_minute1, number_imgIds[minute/10]);
//		remoteViews.setImageViewResource(R.id.imgv_minute2, number_imgIds[minute%10]);
	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		System.out.println("onUpdate");
		AppWidgetManager appWidgetmanager = AppWidgetManager.getInstance(context);
		
		Intent service = new Intent(context, WidgetService.class);
		context.startService(service);
		
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.transparentwidget);
		
		//在这里设置打开一个新的activity
		Intent intent2 = new Intent();
		intent2.setAction(AlarmClock.ACTION_SET_ALARM);
		PendingIntent pendingIntent2 = PendingIntent.getActivity(context, 0, intent2, 0);
		remoteViews.setOnClickPendingIntent(R.id.widget_tv_time, pendingIntent2);
		
		//在这里打开分享列表
//		Intent intent3=new Intent(Intent.ACTION_SEND);   
//		intent3.setType("text/plain");   
//		intent3.putExtra(Intent.EXTRA_SUBJECT, "分享天气");   
//		intent3.putExtra(Intent.EXTRA_TEXT, "分享天气的内容");    
//		intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
//		Intent.createChooser(intent3, "分享");
//		PendingIntent pendingIntent3 = PendingIntent.getActivity(context, 0, intent3, 0);
//		remoteViews.setOnClickPendingIntent(R.id.widget_tv_note, pendingIntent3);
		
		//刷新widget
		int[] appIds = appWidgetmanager.getAppWidgetIds(new ComponentName(context, MyWidgetProvider.class));
		appWidgetManager.updateAppWidget(appIds, remoteViews);
		
	}
}
